<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加人员' : '编辑人员'"
    width="30%"
    align-center
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <ElFormItem label="姓名" prop="employeeName">
        <ElInput v-model="formData.employeeName" />
      </ElFormItem>
      <ElFormItem label="手机号" prop="employeePhone">
        <ElInput v-model="formData.employeePhone" />
      </ElFormItem>
      <ElFormItem label="性别" prop="employeeGender">
        <ElSelect v-model="formData.employeeGender">
          <ElOption label="男" :value=1 />
          <ElOption label="女" :value=2 />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="部门" prop="deptId">
        <ElSelect 
          v-model="formData.deptId"
          placeholder="请选择部门"
          clearable
          filterable
        >
          <ElOption
            v-for="dept in deptList.filter(d => d.id !== undefined)"
            :key="dept.id"
            :value="dept.id!"
            :label="dept.deptName"
          />
        </ElSelect>
      </ElFormItem>
      
      <ElFormItem label="登录账号" prop="loginName">
        <ElInput v-model="formData.loginName">
          <template #suffix>
            <ElTooltip content="默认密码为手机号后六位" placement="top">
              <ElIcon style="cursor: pointer; color: #909399;">
                <Warning />
              </ElIcon>
            </ElTooltip>
          </template>
        </ElInput>
      </ElFormItem>
      
      <ElFormItem label="职务" prop="positionId">
        <ElSelect 
          v-model="formData.positionId" 
          placeholder="请选择职务"
          clearable
          filterable
        >
          <ElOption
            v-for="position in positionList.filter(p => p.id !== undefined)"
            :key="position.id"
            :value="position.id!"
            :label="position.positionName"
          />
        </ElSelect>
      </ElFormItem>
      
     <ElFormItem label="标签" prop="tagList">
        <ElSelect 
          v-model="formData.tagList" 
          placeholder="请选择标签"
          multiple
          clearable
          filterable
          collapse-tags
          collapse-tags-tooltip
        >
          <ElOption
            v-for="tag in tagList.filter(t => t.id !== undefined)"
            :key="tag.id"
            :value="tag.id!"
            :label="tag.tagName"
          />
        </ElSelect>
      </ElFormItem>
      
      <!-- 只在编辑模式下显示状态选择框 -->
      <ElFormItem v-if="dialogType === 'edit'" label="是否禁用" prop="disabledFlag">
        <ElSelect v-model="formData.disabledFlag" placeholder="请选择状态">
          <ElOption label="否" :value=0 />
          <ElOption label="是" :value=1 />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage, ElIcon, ElTooltip } from 'element-plus'
  import { Warning } from '@element-plus/icons-vue'
  import { 
    apiEmployeeSaveDataUsingPost,
    apiEmployeeUpdateDataUsingPost,
    apiPositionPageDataUsingPost,
    apiTagListDataUsingPost,
    apiDeptTreeDataUsingPost,
    type ApiPositionVo,
    type ApiTagVo,
    type ApiDeptTreeVo
  } from '@/api'

  interface Props {
    visible: boolean
    type: string
    userData?: any
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 部门列表数据
  const deptList = ref<ApiDeptTreeVo[]>([])
  
  // 职务列表
  const positionList = ref<ApiPositionVo[]>([])
  
  // 标签列表
  const tagList = ref<ApiTagVo[]>([])

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  // 表单实例
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive({
    id: undefined as number | undefined,
    employeeName: '',
    employeePhone: '',
    employeeGender: undefined as number | undefined,
    deptId: undefined as number | undefined,
    positionId: undefined as number | undefined,
    tagList: [] as number[],
    loginName: '',
    disabledFlag: 0
  })

  // 表单验证规则
 const rules: FormRules = {
    employeeName: [
      { required: true, message: '请输入姓名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    employeePhone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    employeeGender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
    deptId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
    loginName: [
      { required: true, message: '请输入登录账号', trigger: 'blur' },
      { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
    ],
    tagList: [
      { 
        // required: true, 
        message: '请至少选择一个标签', 
        trigger: 'change',
        type: 'array'
        // min: 1
      }
    ]
  }

  // 加载部门列表
  const loadDeptList = async () => {
    try {
      const res = await apiDeptTreeDataUsingPost({
        options: {}
      })
      if (res.length > 0) {
        // 将树形结构扁平化为列表，便于下拉框使用
        deptList.value = flattenDeptTree(res)
      }
    } catch (error) {
      console.error('加载部门列表失败:', error)
    }
  }
  
  // 扁平化部门树
  const flattenDeptTree = (tree: ApiDeptTreeVo[]): ApiDeptTreeVo[] => {
    const result: ApiDeptTreeVo[] = []
    const flatten = (nodes: ApiDeptTreeVo[], level: number = 0) => {
      nodes.forEach(node => {
        result.push({
          ...node,
          deptName: '  '.repeat(level) + node.deptName // 添加层级缩进
        })
        if (node.children && node.children.length > 0) {
          flatten(node.children, level + 1)
        }
      })
    }
    flatten(tree)
    return result
  }
  
  // 加载职务列表
  const loadPositionList = async () => {
    try {
      const res = await apiPositionPageDataUsingPost({
        body: {
          current: 1,
          size: 1000 // 加载所有职务
        }
      })
      if (res?.list) {
        positionList.value = res.total > 0 ? res.list : []
      }
    } catch (error) {
      console.error('加载职务列表失败:', error)
    }
  }
  
  // 加载标签列表
  const loadTagList = async () => {
    try {
      const res = await apiTagListDataUsingPost({
        body: {}
      })
      if(res) {
        tagList.value = res.length > 0 ? res : []
      }
    } catch (error) {
      console.error('加载标签列表失败:', error)
    }
  }

  // 初始化表单数据
   const initFormData = () => {
    const isEdit = props.type === 'edit' && props.userData
    const row = props.userData

    Object.assign(formData, {
      id: isEdit ? row.id : undefined,
      employeeName: isEdit ? row.employeeName || '' : '',
      employeePhone: isEdit ? row.employeePhone || '' : '',
      employeeGender: isEdit ? row.employeeGender : undefined,
      deptId: isEdit ? row.deptId : undefined,
      positionId: isEdit ? row.positionId : undefined,
      tagList: isEdit && row.tagList ? row.tagList.map((tag: ApiTagVo) => tag.id!).filter((id: number) => id !== undefined) : [],
      loginName: isEdit ? row.loginName : '',
      disabledFlag: isEdit && row.disabledFlag !== undefined ? row.disabledFlag : 0  // 默认启用状态
    })
  }

  // 统一监听对话框状态变化
  watch(
    () => [props.visible, props.type, props.userData],
    ([visible]) => {
      if (visible) {
        // 加载下拉数据
        loadDeptList()
        loadPositionList()
        loadTagList()
        initFormData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate((valid) => {
      if (valid) {
        const submitData: any = {
          employeeName: formData.employeeName,
          employeePhone: formData.employeePhone,
          employeeGender: formData.employeeGender,
          deptId: formData.deptId,
          positionId: formData.positionId,
          loginName: formData.loginName,
          tagIdList: formData.tagList,
          disabledFlag: formData.disabledFlag
        }
        
        if (dialogType.value === 'add') {
          // 添加人员时调用保存接口
          apiEmployeeSaveDataUsingPost({
            body: submitData
          }).then(res => {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            emit('submit')
          }).catch(error => {
            console.error('添加失败:', error)
            ElMessage.error('添加失败')
          })
        } else if (dialogType.value === 'edit') {
          submitData.id = formData.id
          apiEmployeeUpdateDataUsingPost({
            body: submitData
          }).then(res => {
            ElMessage.success('编辑成功')
            dialogVisible.value = false
            emit('submit')
          }).catch(error => {
            console.error('编辑失败:', error)
            ElMessage.error('编辑失败')
          })
        }
      }
    })
  }
</script>